package controll
{
	import events.DataManagerEvent;
	
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.utils.ByteArray;
	
	import gzgi.utils.TimeUtil;
	
	import module.ProjectEventModule;
	import module.ProjectModuleBase;
	
	import views.ProjectBoard;

	public class XMLDataManager extends DataManager implements IDataManager
	{
		private var m_xml:XML;
		private static var m_instance:IDataManager;
		public static const XML_PATH:String = File.applicationDirectory.nativePath + "/xml/data.xml";
		private static const PARTICIPATORLIST_SPLIT_OPERATOR:String = "|";
		public function XMLDataManager()
		{
			super();
			initXML();
		}
		
		private function initXML():void
		{
			try
			{
				var file:File = new File(XML_PATH);
				var filestream:FileStream = new FileStream();
				var byteArray:ByteArray = new ByteArray();
				
				filestream.open(file, FileMode.UPDATE);
				filestream.readBytes(byteArray, 0, filestream.bytesAvailable);
				byteArray.uncompress();
				m_xml = byteArray.readObject() as XML;
			}
			catch($err:Error)
			{
				m_xml = null;
			}
			if (m_xml == null)
			{
				m_xml = <tree></tree>;
			}
			trace (m_xml);
			ProjectEventModule.setGlobalId(Number(m_xml.globalId));
			ProjectorLogger.getInstance().logger("xml loaded");
		}
		private function transfromXMLToDataModule(xml:XML):ProjectEventModule
		{
			var data:ProjectEventModule = new ProjectEventModule();
			data._title(xml.attribute("title"));
			data._id(Number(xml.attribute("id")));
			data._startTime(new Date(Date.parse(xml.attribute("startTime"))));
			data._endTime(new Date(Date.parse(xml.attribute("endTime"))));
			data._progress(Number(xml.attribute("progress")));
			data._participatorList(xml.attribute("participatorList").toString().split(PARTICIPATORLIST_SPLIT_OPERATOR));
			return data;
			
		}
		public function loadEventPanelList($comeFromSource:ProjectBoard, $startDate:Date, $daysCount:Number):void
		{
			var vec:Vector.<ProjectEventModule> = new Vector.<ProjectEventModule>();
			
			var startDayIndex:Number = TimeUtil.getDateIndexFrom1970($startDate);
			var endDayIndex:Number = startDayIndex + $daysCount - 1;
			var list:XMLList = m_xml.eventPanels.eventPanel.(!(@startTimeIndex > endDayIndex || @endTimeIndex < startDayIndex));
			
			for (var i:uint = 0; i < list.length(); i++)
			{
				vec.push(transfromXMLToDataModule(list[i] as XML));
			}
			var event:DataManagerEvent = new DataManagerEvent(DataManagerEvent.EVENT_PANELS_LOADED);
			event.data = vec;
			event.projectBoard = $comeFromSource;
			this.dispatchEvent(event);
		}
		public function insertEventPanel($data:ProjectEventModule):void
		{
			var xml = <eventPanel id={$data.id} title={$data.title} 
						startTime={$data.startTime} endTime={$data.endTime} 
						progress={$data.progress} participatorList={$data.participatorList.join(PARTICIPATORLIST_SPLIT_OPERATOR)}
						startTimeIndex={TimeUtil.getDateIndexFrom1970($data.startTime)}
						endTimeIndex={TimeUtil.getDateIndexFrom1970($data.endTime)}
						>
						<descript>{$data.descript}</descript>
						</eventPanel>;
			m_xml.eventPanels.childNode = xml;
			m_xml.globalId = $data.id;
			var event:DataManagerEvent = new DataManagerEvent(DataManagerEvent.EVENT_PANEL_INSERTED);
			this.dispatchEvent(event);
			ProjectorLogger.getInstance().logger("xml inserted:\n" + xml);
		}
		public function updateEventPanel($data:ProjectEventModule):void
		{
			var xmlList:XMLList = m_xml.eventPanels.eventPanel.(@id == $data.id);
			if (xmlList.length() > 0)
			{
				var xml:XML = xmlList[0] as XML;
				xml.@title = $data.title;
				xml.@startTime = $data.startTime;
				xml.@endTime = $data.endTime;
				xml.@progress = $data.progress;
				xml.@startTimeIndex = TimeUtil.getDateIndexFrom1970($data.startTime);
				xml.@endTimeIndex = TimeUtil.getDateIndexFrom1970($data.endTime);
				xml.@participatorList = $data.participatorList.join(PARTICIPATORLIST_SPLIT_OPERATOR);
				ProjectorLogger.getInstance().logger("xml updated:\n" + xml);
			}
		}
		public function deleteEventPanel($data:ProjectEventModule):void
		{
			
		}
		public function close():void
		{
			try
			{
				if (m_xml != null)
				{
					var byteArray:ByteArray = new ByteArray();
					byteArray.writeObject(m_xml);
					byteArray.compress();
					var file:File = new File(XML_PATH);
					var fileStream:FileStream = new FileStream();
					fileStream.open(file, FileMode.WRITE);
					fileStream.position = 0;
					fileStream.writeBytes(byteArray, 0, byteArray.length);
					fileStream.close();
					ProjectorLogger.getInstance().logger("xml file saved:\n");
				}
			}
			catch($err:Error)
			{
				trace ($err.getStackTrace());
				ProjectorLogger.getInstance().logger("file save error:\n" + $err.getStackTrace());
			}
		}
	}
}